<?php

namespace app\storeapi\model;
use org\Redis;
use think\Model;
use app\common\exception\BaseException;

/**
 * 微信小程序模型
 * Class Wxapp
 * @package app\common\model
 */
class Wxapp extends Base
{
    protected $name = 'wxapp';

    /**
     * 获取小程序收款码
     * @param int|null $wxappId
     * @return static|null
     * @throws \think\exception\DbException
     */
    public static function code($wxappId = null)
    {
        $list = static::get($wxappId ?:[],['image']);
        $code = $list['image']['file_path']?:"";
        return $code;
    }

    /**
     * 关联小程序二维码图
     * @return \think\model\relation\HasOne
     */
    public function image()
    {
        return $this->hasOne("UploadFile", 'file_id', 'image_id');
    }

    /**
     * 获取小程序信息
     * @param int|null $wxappId
     * @return static|null
     * @throws \think\exception\DbException
     */
    public static function detail($wxappId = null)
    {
        return static::get($wxappId ?: []);
    }

    /**
     * 从缓存中获取小程序信息
     * @param int|null $wxappId 小程序id
     * @return array $data
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public static function getWxappInfo($wxappId = null)
    {
        // 小程序id
        $redis = new Redis();
        if(is_null($wxappId)) throw new BaseException(['msg' => self::ERROR_MSG_APPID]);
        if (!$data = $redis->get('wxapp_'.$wxappId)) {
            // 获取小程序详情, 解除hidden属性
            $detail = self::detail($wxappId)->hidden([], true);
            if (empty($detail)) throw new BaseException(['msg' => self::ERROR_MSG_NOFIND]);
            // 写入缓存
            $data = $detail->toArray();
            $redis->set('wxapp_'.$wxappId,$data);
        }
        return $data;
    }

}
